<?php
/**
 * admin service file Created by PhpStorm.
 * User: yang
 * Date: 2020/06/11
 */

namespace App\Http\Service\Web;

use Common\Repository\UserRepository;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Session;

class UserLoginService
{
    /**
     * 注册操作
     * @param array $post_data
     * @return array
     */
    public function register($post_data = [])
    {
        try {
            if ($post_data['password'] != $post_data['pass']) {
                return hello_error('两次输入密码不一致！');
            }
            $pass = preg_match('/^(\w*(?=\w*\d)(?=\w*[A-Za-z])\w*){6,16}$/', $post_data['password']);
            if (!$pass) {
                return hello_error('请输入6-16位由英文/数字组成的密码！');
            }
            $post_data['head_img'] = mt_rand(0, 10);
            $post_data['password'] = Hash::make($post_data['password']);
            $result = UserRepository::addOne($post_data);

            if ($result) {
                return json_success('注册成功');
            }

            return hello_error('添加失败！');
        } catch (\Exception $exception) {
            return hello_error('失败！', $exception->getMessage());
        }
    }

    /**
     * 登录操作
     * @param array $post_data
     * @return array
     */
    public function logined($post_data = [])
    {
        try {
            $where['where'] = ['name' => $post_data['name']];
            $where['orWhere'] = ['email' => $post_data['email']];
            //$where['orWhere'] = ['phone' => $post_data['phone']];
            $where['field'] = ['id', 'status', 'name', 'login_times'];
            $user = UserRepository::getOne($where);

            //自带验证，里面传验证字段
            $data = ['name' => $user['name'], 'password' => $post_data['password']];
            if (web_user()->attempt($data)) {

                //更新最后登录时间
                $upData = [
                    'id' => $user['id'],
                    'login_times' => $user['login_times'] + 1,
                    'updated_at' => date('Y-m-d H:i:s')
                ];
                UserRepository::editOne($upData);

                return json_success('登录成功');
            }

            return json_error('用户名或密码错误');
        } catch (\Exception $exception) {
            return hello_error('失败！', $exception->getMessage());
        }
    }

    /**
     * 退出登录
     * @return array
     */
    public function logout()
    {
        try {
            //退出登录
            web_user()->logout();

            //清除全部session
            Session::flush();

            //重定向
            return redirect()->route('login');

        } catch (\Exception $exception) {
            return hello_error('失败！', $exception->getMessage());
        }
    }


}